<template>
  <div class="parameter">
    <el-card>
      <div class="parameter_top" :width="pararWidth">
        <el-button class="back" @click="goBack">返回</el-button>
        <!-- <el-button v-if="showmoban" @click="handlergomoban"
          >查看模版列表</el-button
        > -->
        <div class="btn">
          <el-button @click="handlerRead">读取参数</el-button>

          <el-button
            style="background-color:#000;color:#fff"
            @click="handlershowmoban"
            >模版另存为</el-button
          >
          <el-button type="primary" class="test" @click="showTest"
            >同步测试</el-button
          >
          <el-button type="success" class="upload" @click="showUpload"
            >保存</el-button
          >
        </div>
      </div>
      <el-table
        :data="paramterList"
        border
        style="width: 100%;margin-top:70px"
        height="850"
      >
        <el-table-column
          prop="name"
          label="菜单名称"
          width="180"
        ></el-table-column>
        <el-table-column prop="describe" label="菜单描述"></el-table-column>
        <el-table-column
          prop="position"
          label="参数位置"
          width="80"
        ></el-table-column>
        <el-table-column prop="value" label="设定范围值"></el-table-column>
        <el-table-column prop="currentValue" label="当前参数值" width="300">
          <template slot-scope="scoped">
            <div class="rowINput">
              <div style="margin-top:9px;">{{ scoped.row.currentValue }}</div>
              <!-- <i class="el-icon-edit" @click="showInput" style="padding-left:20px;padding-top:7px;cursor:pointer;"></i> -->
              <el-input
                placeholder="请输入参数值"
                v-model="value1[scoped.row.position]"
                @change="handlerPageNo($event, scoped.row)"
                style="width:200px;margin-left:20px"
              ></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="参数值类型">
          <template slot-scope="scoped">
            <div>
              <el-tag type="success" v-if="scoped.row.type == 1">范围型</el-tag>
              <el-tag type="info" v-else-if="scoped.row.type == 2"
                >固定值型</el-tag
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="company" label="单位"></el-table-column>
      </el-table>

      <!-- <el-dialog title="参数配置" :visible.sync="dialogVisible" width="70%" :before-close="handleClose">
        <div v-for="(item, index) in ruleForm.dynamicItem " :key="index">
          <el-form
            :model="ruleForm"
            ref="ruleFormRef"
            label-width="100px"
            class="demo-ruleForm"
            :inline="true"
          >
            <el-form-item
              label="菜单名称"
              prop="position"
              :prop="'dynamicItem.' + index + '.position'"
              :rules="{
            required: true, message: '菜单名称不能为空', trigger: 'blur'
        }"
            >
              <el-select v-model="item.position" placeholder="请选择菜单名称" @change="handlerChange">
                <el-option
                  v-for="subitem in ThermostatList"
                  :label="subitem.name"
                  :value="subitem.position"
                  :key="subitem.position"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="菜单值"
              prop="value"
              :prop="'dynamicItem.' + index + '.value'"
              :rules="{
            required: true, message: '菜单值不能为空', trigger: 'blur',
        }"
            >
              <el-input v-model="item.value" style="width:350px" placeholder="请输入菜单值"></el-input>
            </el-form-item>
            <el-form-item>
              <i class="el-icon-delete" @click="deleteItem(item, index)" style="cursor:pointer "></i>
            </el-form-item>
          </el-form>
        </div>
        <el-link icon="el-icon-plus" type="success" @click="addItem" style="margin-left:30px">新增参数</el-link>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handlerQu">取 消</el-button>
          <el-button type="primary" @click="handlerSure">保存参数配置</el-button>
        </span>
      </el-dialog>-->

      <!-- 点击同步测试 -->
      <el-dialog
        title="同步测试"
        :visible.sync="dialogVisibleTest"
        width="30%"
        :before-close="handleClose"
      >
        <el-form
          :inline="true"
          :model="copyForm"
          :rules="copyrules"
          ref="copyRef"
          class="demo-form-inline"
        >
          <!-- <el-form-item>
            <el-button type="success" @click="handlerDefalut">默认值同步</el-button>
            <el-button @click="handlerShiji">实际值同步</el-button>
          </el-form-item>-->
          <el-form-item label="复制的模板" prop="theFormId">
            <el-select
              v-model="copyForm.theFormId"
              placeholder="请选择复制的模板"
            >
              <el-option
                v-for="item in copyList"
                :label="item.name"
                :value="item.id"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleTest = false">取 消</el-button>
          <el-button type="primary" @click="handlerTest">确定</el-button>
        </span>
      </el-dialog>

      <!-- 模版另存为 -->
      <el-dialog
        title="模版另存为"
        :visible.sync="dialogVisiblemoban"
        width="30%"
        :before-close="handleClosemoban"
      >
        <el-form
          :model="ruleFormmoban"
          :rules="rulesmoban"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="模版名称" prop="name">
            <el-input
              v-model="ruleFormmoban.name"
              placeholder="请输入模版名称"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisiblemoban = false">取 消</el-button>
          <el-button type="primary" @click="handlermoban">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import {
  getDeviceThermostat,
  getThermostatList,
  sendWriteF1,
  synchroWriteF1,
  sendReadF1,
  getFormworkSelect,
  saveTheFromwork
} from "../../utils/api";
import { mapState, mapGetters } from "vuex";
export default {
  inject: ["reload"],
  data() {
    return {
      // 参数数据
      paramterList: [],
      //   弹框的显示隐藏
      dialogVisible: false,
      //表单输入的值
      ruleForm: {
        position: "",
        value: "",
        dynamicItem: []
      },
      // 已经选中的数据
      checkedarr: [],
      // 同步测试的显示和隐藏
      dialogVisibleTest: false,
      value1: [],
      showshu: false,
      //   模板信息列表
      copyList: [],
      // 模板的弹框
      copyForm: {
        theFormId: "",
        uid: window.sessionStorage.getItem("deviceuid")
      },
      // 模板的校验
      copyrules: {
        theFormId: [{ required: true, message: "请选择模板", trigger: "blur" }]
      },
      //
      positionList: [],
      dialogVisiblemoban: false,
      ruleFormmoban: {
        name: "",
        uid: window.sessionStorage.getItem("deviceuid"),
        companyId: ""
      },
      rulesmoban: {
        name: [{ required: true, message: "请输入模版名称", trigger: "blur" }]
      },
      roleList: [],
      showmoban: true,
      newvalue: "",
      pararWidth: ""
    };
  },
  computed: {
    ...mapState(["org_id"])
  },
  watch: {
    org_id(val) {
      this.getCopy();
    }
  },
  created() {
    this.getDataInit();
    this.getParamter();
    this.pararWidth = document.documentElement.clientWidth + 150;
    this.roleList = JSON.parse(window.sessionStorage.getItem("list"));
    for (var i = 0; i < this.roleList.length; i++) {
      if (this.roleList[i].name == "模板列表" && this.roleList[i].id == 323) {
        this.showmoban = true;
      } else {
        this.showmoban = false;
      }
    }
  },
  methods: {
    handlershowmoban() {
      this.dialogVisiblemoban = !this.dialogVisiblemoban;
    },
    handlergomoban() {
      this.$router.push("/TemplateList");
    },
    // 点击另存为模版
    handlermoban() {
      this.ruleFormmoban.companyId = this.org_id;
      this.postRequest(saveTheFromwork, this.ruleFormmoban).then(res => {
        if (res.code == 200) {
          this.$message.success("另存为模版成功");
          this.getDataInit();
          this.dialogVisiblemoban = false;
        }
      });
    },
    handleClosemoban() {
      this.ruleFormmoban.name = "";

      this.dialogVisiblemoban = false;
    },
    getDataInit() {
      if (this.org_id === "" || this.org_id === null || !this.org_id) {
      } else {
        this.getParamter();
        this.getCopy();
      }
    },
    //   获取模板信息(供复制使用)
    getCopy() {
      this.postRequest(getFormworkSelect, { companyId: this.org_id }).then(
        res => {
          if (res.code == 200) {
            this.copyList = res.data;
          }
        }
      );
    },
    // 点击确定
    handlerTest() {
      this.$refs.copyRef.validate(valid => {
        if (!valid) return this.$message.error("请填写完整");
        const loading = this.$loading({
          lock: true,
          text: "配置中,请勿关闭!",
          background: "rgba(0, 0, 0, 0.5)"
        });
        this.postRequest(synchroWriteF1, this.copyForm).then(res => {
          if (res.code == 200) {
            loading.close();
            this.$message.success("同步测试成功");
            this.dialogVisibleTest = false;
            this.getParamter();
            this.$refs.copyRef.resetFields();
          }
        });
      });
    },
    // 返回上一级
    goBack() {
      this.$store.dispatch("delVisitedViews", this.$route).then(obj => {
        this.$router.push("/PlatformEquipment");
      });
      window.sessionStorage.removeItem("deviceuid");
    },
    //   获取参数列表
    getParamter() {
      const params = {
        uid: window.sessionStorage.getItem("deviceuid")
      };
      this.postRequest(getDeviceThermostat, params).then(res => {
        if (res.code == 200) {
          this.paramterList = res.data;
        }
      });
    },
    // 点击上传
    // showUpload() {
    //   this.dialogVisible = !this.dialogVisible;
    //   this.getThermostat();
    // },
    //点击铅笔显示输入框
    showInput() {
      this.showshu = !this.showshu;
    },
    // 点击保存

    showUpload() {
      this.ruleForm.dynamicItem.forEach((v, key) => {
        if (v.value == "") {
          this.ruleForm.dynamicItem.splice(key, 1);
        }
      });
      const params = {
        uid: window.sessionStorage.getItem("deviceuid"),
        temdata: JSON.stringify(this.ruleForm.dynamicItem)
      };
      this.postRequest(sendWriteF1, params).then(res => {
        if (res.code == 200) {
          // this.$message.success("保存参数配置成功");

          const loading = this.$loading({
            lock: true,
            text: "配置中,请勿关闭!",
            background: "rgba(0, 0, 0, 0.5)"
          });
          this.$message.success("默认值同步成功");
          // setTimeout(() => {
          //   this.handlersendRead();
          // }, 500);
          this.dialogVisible = false;
          this.reload();
        }
      });
    },
    // 点击读取温控参数
    handlerRead() {
      this.postRequest(sendReadF1, {
        uid: window.sessionStorage.getItem("deviceuid")
      }).then(res => {
        if (res.code == 200) {
          const loading = this.$loading({
            lock: true,
            text: "读取中,请勿关闭!",
            background: "rgba(0, 0, 0, 0.5)"
          });
          setTimeout(() => {
            loading.close();
            this.$message.success("读取成功");
            this.reload();
          }, 500);
        }
      });
    },
    // 拿到值
    handlerPageNo(val, data) {
      if (this.positionList.includes(data.position)) {
        this.ruleForm.dynamicItem.forEach(item => {
          if (item.position == data.position) {
            item.value = val;
          }
        });
      } else {
        this.positionList.push(data.position);
        this.ruleForm.dynamicItem.push({
          position: data.position,
          value: val
        });
      }
    },
    // 动态添加表单
    addItem() {
      this.ruleForm.dynamicItem.push({
        position: "",
        value: ""
      });
    },
    // 动态删除
    deleteItem(item, index) {
      this.ruleForm.dynamicItem.splice(index, 1);
    },
    // 获取菜单名称
    getThermostat() {
      const params = {
        positionJson: ""
      };
      this.postRequest(getThermostatList, params).then(res => {
        if (res.code == 200) {
          this.ThermostatList = res.data;
        }
      });
    },
    // 选择下拉的时候触发这个函数
    handlerChange(val) {
      this.checkedarr.push(val);
      const items = new Set(this.checkedarr);
      const array = Array.from(items);
      const params = {
        positionJson: JSON.stringify(array)
      };
      this.postRequest(getThermostatList, params).then(res => {
        if (res.code == 200) {
          this.ThermostatList = res.data;
        }
      });
    },
    // 点击取消
    handlerQu() {
      this.dialogVisible = false;
      this.ruleForm = {};
      this.ruleForm.dynamicItem = [];
      this.reload();
    },
    // 读取成功的函数
    handlersendRead() {
      const params = {
        uid: window.sessionStorage.getItem("deviceuid")
      };
      this.postRequest(sendReadF1, params).then(res => {
        if (res.code == 200) {
          const loading = this.$loading({
            lock: true,
            text: "配置中,请勿关闭!",
            background: "rgba(0, 0, 0, 0.5)"
          });
          setTimeout(() => {
            loading.close();
            this.$message.success("配置成功");

            this.getParamter();
            this.reload();
          }, 500);
        }
      });
    },
    // 点击同步测试
    showTest() {
      this.dialogVisibleTest = !this.dialogVisibleTest;
    },
    // 默认值同步
    // handlerDefalut() {
    //   const params = {
    //     uid: window.sessionStorage.getItem("deviceuid"),
    //     type: 1
    //   };
    //   this.postRequest(synchroWriteF1, params).then(res => {
    //     if (res.code == 200) {
    //       const loading = this.$loading({
    //         lock: true,
    //         text: "配置中,请勿关闭!",
    //         background: "rgba(0, 0, 0, 0.5)"
    //       });
    // this.$message.success("默认值同步成功");
    //       setTimeout(() => {
    //         this.handlersendRead();
    //       }, 3000);
    //     }
    //   });
    // },
    // 实际值同步
    // handlerShiji() {
    //   const params = {
    //     uid: window.sessionStorage.getItem("deviceuid"),
    //     type: 2
    //   };
    //   this.postRequest(synchroWriteF1, params).then(res => {
    //     if (res.code == 200) {
    //       // this.$message.success("实际值同步成功");
    //       const loading = this.$loading({
    //         lock: true,
    //         text: "配置中,请勿关闭!",
    //         background: "rgba(0, 0, 0, 0.5)"
    //       });
    //       // this.$message.success("默认值同步成功");
    //       setTimeout(() => {
    //         this.handlersendRead();
    //       }, 3000);
    //     }
    //   });
    // },
    // 点击保存参数
    handlerSure() {
      const params = {
        uid: window.sessionStorage.getItem("deviceuid"),
        temdata: JSON.stringify(this.ruleForm.dynamicItem)
      };
      this.postRequest(sendWriteF1, params).then(res => {
        if (res.code == 200) {
          // this.$message.success("保存参数配置成功");

          const loading = this.$loading({
            lock: true,
            text: "配置中,请勿关闭!",
            background: "rgba(0, 0, 0, 0.5)"
          });
          // this.$message.success("默认值同步成功");
          setTimeout(() => {
            this.handlersendRead();
          }, 500);
          this.dialogVisible = false;
          this.getParamter();
          this.ruleForm = {};
          this.ruleForm.dynamicItem = [];
        } else {
          this.ruleForm.dynamicItem = [];
        }
      });
    },
    // 关闭弹框触发的函数
    handleClose() {
      this.ruleForm = {};
      this.ruleForm.dynamicItem = [];
      this.dialogVisible = false;
      this.reload();
    }
  }
};
</script>
<style lang="less" scoped>
.parameter {
  position: relative;
  .rowINput {
    display: flex;
    flex-direction: row;
    flex: 1;
    margin-left: 10px;
  }
  .parameter_top {
    position: fixed;
    margin-bottom: 30px;
    display: flex;
    width: 90%;
    padding: 10px;
    z-index: 1;
    background: #cccccc;
    .btn {
      margin-left: auto;
    }
  }
}
</style>
